﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;

namespace Admin.Helpers
{
    public static class ExeStoreProc
    {



        public static List<T> ExecuteStoredProcedure<T>(this DbContext dbContext, string storedProcedureName, params object[] parameters)
        {
            string storedProcedureCommand = "CALL " + storedProcedureName + "(";

            List<object> augmentedParameters = parameters.ToList();

            MySqlParameter[] queryParams;
            storedProcedureCommand = AddParametersToCommand(storedProcedureCommand, augmentedParameters, out queryParams);

            storedProcedureCommand += ");";

            return dbContext.Database.SqlQuery<T>(storedProcedureCommand, queryParams).ToList<T>();
        }



        private static string AddParametersToCommand(string storedProcedureCommand, List<object> augmentedParameters, out MySqlParameter[] queryParams)
        {
            string paramName = "";
            queryParams = new MySqlParameter[augmentedParameters.Count()];
            for (int i = 0; i < augmentedParameters.Count(); i++)
            {
                paramName = "p" + i;
                queryParams[i] = new MySqlParameter(paramName, augmentedParameters[i]);
                storedProcedureCommand += "@" + paramName;

                if (i < augmentedParameters.Count - 1)
                {
                    storedProcedureCommand += ",";
                }
            }
            return storedProcedureCommand;
        }

    }
}